import {AfterViewInit, Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {DvbConfigService} from '../../../../../../services/api/dvb-config.service';
import {ChartComponent, WebsocketService} from '../../../../../../../ng-tools';
import {DatePipe} from '@angular/common';

@Component({
  selector: 'device-memory-usage',
  templateUrl: './device-memory-usage.component.html',
  styleUrls: ['./device-memory-usage.component.scss']
})
export class DeviceMemoryUsageComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('deviceMemoryChart') private deviceMemoryChart: ChartComponent;
  cpuChartOptions: any;
  deviceSocket;
  interval;
  xData = [];
  cpuChartSize = {width: '700px', height: '200px'};

  constructor(private dvbConfigService: DvbConfigService,
              private socket: WebsocketService,
              private datePipe: DatePipe) {
    this.cpuChartOptions = {
      title: {
        show: false,
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any[]) => {
          let template = `<span>时间：${params[0].axisValue}</span>`;
          params.forEach((data) => {
            const cpuLoad = (data.data).toString() + '%';
            template = template + `<br/><span>${data.seriesName}：${cpuLoad}</span>`;
          });
          return template;
        }
      },
      legend: {
        animation: false
      },
      grid: {
        top: '10%',
        left: '1%',
        right: '1%',
        bottom: '1%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []
      },
      yAxis: {
        type: 'value',
        interval: 25,
        max: 100,
        min: 0,
        axisLabel: {
          formatter: '{value}%'
        },
        axisTick: {
          show: false
        }
      },
      series: [
        {
          name: '内存使用率',
          type: 'line',
          symbol: 'none',
          data: [],
          lineStyle: {
            width: 1
          }
        },
      ]
    };
  }

  ngOnInit() {
  }

  ngAfterViewInit(): void {
    const timestaps = [];
    const date = new Date();
    for (let i = 0; i < 60; i++) {
      timestaps.push(date.getTime() + i * 1000);
    }
    for (const time of timestaps) {
      this.xData.push(this.datePipe.transform(Math.floor(time), 'HH:mm:ss'));
    }
  }

  setChartData(runData) {
    this.cpuChartOptions.xAxis.data = this.xData;
    this.cpuChartOptions.series = this.cpuChartOptions.series.map((series, index) => {
      if (series.data.length <= 60) {
        series.data.push(parseFloat(runData.memory));
        // this.cpuChartOptions.xAxis.data.push(
        //   this.datePipe.transform(Math.floor(runData.time / 1000), 'HH:mm:ss')
        // );
      } else {
        if (index === 0) {
          // x轴的值只需要添加一次
          this.cpuChartOptions.xAxis.data.shift();
          this.cpuChartOptions.xAxis.data.push(
            this.datePipe.transform(Math.floor(runData.time / 1000), 'HH:mm:ss')
          );
        }
        series.data.shift();
        series.data.push(parseFloat(runData.memory));
      }
      return series;
    });
    this.deviceMemoryChart.setOption({
      xAxis: this.cpuChartOptions.xAxis,
      series: this.cpuChartOptions.series
    });
  }

  getDataBySocket() {
    this.dvbConfigService.configObserver().subscribe((config) => {
      this.deviceSocket = this.socket.socket(config.baseWebSocketUrl + this.dvbConfigService.urls.realTimeInfo);
      this.deviceSocket.onmessage = (evt) => {
        const data = JSON.parse(evt.data);
        this.setChartData(data);
      };
      this.deviceSocket.onopen = () => {
        this.socket.send(this.deviceSocket, {});
        this.interval = this.socket.interval(this.deviceSocket, 1000, {});
      };
      this.deviceSocket.onclose = () => {
        clearInterval(this.interval);
      };
    });
  }
  release() {
    if (this.deviceSocket && this.deviceSocket.readyState === 1) {
      this.deviceSocket.close();
    }
  }
  startMonitor() {
    this.deviceMemoryChart.setOption(this.cpuChartOptions);
    this.getDataBySocket();
  }

  ngOnDestroy(): void {
    this.release();
  }
}
